<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams">
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('sysDept.name')" prop="likeDeptName">
              <el-input
                v-model="queryParams.likeDeptName"
                :placeholder="$t('sysDept.nameRequired')"
                class="!w-[203px]"
                clearable
                @keyup.enter="tableHooks.handleQuery()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysDept.type')" prop="deptType">
              <jmash-dict-select
                v-model="queryParams.deptType"
                :placeholder="$t('sysDept.typeRequired')"
                :type-code="Constant.DICT_DEPT_TYPE"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('sysDept.status')" prop="status">
              <el-select
                v-model="queryParams.status"
                :placeholder="$t('sysDept.statusRequired')"
                class="!w-[203px]"
                clearable
              >
                <el-option :label="$t('common.enable')" :value="true" />
                <el-option :label="$t('common.disable')" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="search-btn">
              <el-button type="primary" @click="tableHooks.handleQuery()">
                {{ $t("common.search") }}
              </el-button>
              <el-button @click="tableHooks.resetQuery()">
                {{ $t("common.reset") }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="clear"></div>
    </div>
    <!-- 条件查询区域结束 -->
    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <el-row justify="space-between">
          <el-col :span="17">
            <el-button
              v-hasPerm="['rbac:dept:add']"
              type="primary"
              @click="handleAdd"
            >
              {{ $t("common.add") }}
            </el-button>
            <el-button
              v-hasPerm="['rbac:dept:delete']"
              type="primary"
              @click="tableHooks.deleteRecords()"
            >
              {{ $t("common.batchDelete") }}
            </el-button>
            <el-dropdown
              v-hasPerm="['rbac:dept:enable']"
              class="dropdown-left"
              @command="enableRecords"
            >
              <el-button type="primary">
                {{ $t("common.enable") }}/{{ $t("common.disable") }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="true">
                    <el-icon size="14">
                      <Unlock />
                    </el-icon>
                    {{ $t("common.enable") }}
                  </el-dropdown-item>
                  <el-dropdown-item command="false">
                    <el-icon size="14">
                      <Lock />
                    </el-icon>
                    {{ $t("common.disable") }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="7" class="container-float">
            <el-button
              v-hasPerm="['rbac:dept:import']"
              class="dropdown-left"
              plain
              type="primary"
              @click="uploadVisible = true"
            >
              {{ $t("common.import") }}
            </el-button>
            <el-button
              v-hasPerm="['rbac:dept:export']"
              plain
              type="primary"
              @click="tableHooks.handleExport(t('sysDept.name'))"
            >
              {{ $t("common.export") }}
            </el-button>
            <jmash-column-select
              v-model="tableLabel"
              label-name="rbac/rbac-dept"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 按钮结束 -->

      <!-- 表格开始 -->
      <jmash-table
        ref="multipleTableRef"
        row-key="deptId"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        @selection-change="tableSelected"
        @sort-change="handleSort"
      >
        <template #type="scope">
          <span>{{
            Dict.deptTypeDict.getDictValue(scope.data.row.deptType)
          }}</span>
        </template>
        <template #isOpen="scope">
          <span v-if="scope.data.row.isOpen">开放访问</span>
          <span v-else>授权访问</span>
        </template>
        <template #status="scope">
          <el-switch
            v-model="scope.data.row.status"
            @change="
              tableHooks.enableRecord(scope.data.row, scope.data.row.status)
            "
          />
        </template>
        <!-- 排序 -->
        <template #sort="scope">
          <el-icon
            size="16"
            @click="tableHooks.handleMove(scope.data.row, false)"
          >
            <Bottom />
          </el-icon>
          <el-icon
            size="16"
            @click="tableHooks.handleMove(scope.data.row, true)"
          >
            <Top />
          </el-icon>
        </template>
        <template #operation="scope">
          <span
            v-hasPerm="['rbac:dept:update']"
            class="el-button-color"
            @click="handleEdit(scope.data.row)"
          >
            {{ $t("common.edit") }}
          </span>
          <span
            v-hasPerm="['rbac:dept:delete']"
            class="el-button-color dropdown-left"
            @click="tableHooks.deleteRecord(scope.data.row)"
          >
            {{ $t("common.delete") }}
          </span>
        </template>
      </jmash-table>
    </el-card>
    <dept-edit
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      :entity-key="entityKey"
      width="800px"
      @refresh="refresh"
    />
    <import-upload
      v-if="uploadVisible"
      :upload-visible="uploadVisible"
      :template-title="$t('sysMenu.templateDownload')"
      @template-down="tableHooks.downloadTemplate(t('sysDept.name'))"
      @import-events="importExcel"
      @upload-closed="uploadClosed"
    />
  </div>
</template>
<script setup lang="ts">
import { type Ref, ref, reactive } from "vue";
import {
  type TableColumn,
  type TableSort,
  type DialogRef,
  useTableHooks,
} from "jmash-core";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { ElMessage, ElMessageBox } from "element-plus";
import { Constant } from "@/constant";
import { Dict } from "@/api/system/index";
import deptEdit from "./edit.vue";
import { deptApi } from "@/api/system/dept/index";
import type {
  DeptReq,
  DeptKey,
  DeptModel,
  DeptImportReq,
} from "@/api/system/dept/types";

const queryParams = ref<DeptReq>({});
const tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "sysDept.code",
    prop: "deptCode",
    isColumn: true,
  },
  {
    label: "sysDept.name",
    prop: "deptName",
    isColumn: true,
  },
  {
    label: "sysDept.type",
    prop: "deptType",
    isColumn: true,
    slotName: "type",
    columnType: "slot",
  },
  {
    label: "sysDept.accessPermiss",
    prop: "isOpen",
    isColumn: true,
    slotName: "isOpen",
    columnType: "slot",
  },
  {
    label: "sysDept.status",
    prop: "status",
    slotName: "status",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "sysDept.sort",
    slotName: "sort",
    columnType: "slot",
    isColumn: true,
  },
  {
    label: "common.operate",
    width: "200",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    isColumn: true,
  },
]);

const dialog: DialogRef = reactive({
  title: "",
  visible: false,
});
const uploadVisible = ref(false);
const { tableHooks, multipleTableRef, queryFormRef, listLoading, tableData } =
  useTableHooks(t, deptApi, queryParams);

let entityKey = reactive<DeptKey>({});

function tableSelected(value: DeptModel[]) {
  tableHooks.selectionRows.value = value;
}

// 导入Excel.
function importExcel(val: DeptImportReq) {
  val.updateMask = "";
  tableHooks.importExcel(val).then(() => {
    uploadVisible.value = false;
  });
}

// 关闭导入弹框
function uploadClosed() {
  uploadVisible.value = false;
}

// 新增
function handleAdd() {
  entityKey = reactive<DeptKey>({});
  dialog.title = t("common.add");
  dialog.visible = true;
}

// 编辑
function handleEdit(row: DeptModel) {
  entityKey.deptId = row.deptId;
  dialog.visible = true;
  dialog.title = t("common.edit");
}

/**
 * 从子组件传过来的事件，刷新列表
 *
 * @returns {void}
 */
function refresh(value: boolean) {
  if (value) {
    tableHooks.getList();
  }
}

function enableRecords(command: string) {
  if (command === "false") {
    if (tableHooks.selectionRows.value.length === 0) {
      ElMessage({
        message: t("common.chooseDisable"),
        type: "warning",
      });
      return;
    }
    ElMessageBox.confirm(t("common.confirmDisable"), t("common.disable"), {
      cancelButtonText: t("common.cancel"),
      confirmButtonText: t("common.confirm"),
      type: "warning",
    })
      .then(() => {
        handleEnable(
          command,
          tableHooks.selectionRows.value.map(
            (item: DeptKey) => item.deptId as string,
          ),
        );
      })
      .catch(() => {});
  } else {
    if (tableHooks.selectionRows.value.length === 0) {
      ElMessage({
        message: t("common.chooseEnable"),
        type: "warning",
      });
      return;
    }
    ElMessageBox.confirm(t("common.confirmEnable"), t("common.enable"), {
      cancelButtonText: t("common.cancel"),
      confirmButtonText: t("common.confirm"),
      type: "warning",
    })
      .then(() => {
        handleEnable(
          command,
          tableHooks.selectionRows.value.map(
            (item: DeptKey) => item.deptId as string,
          ),
        );
      })
      .catch(() => {});
  }
}

// 启用禁用接口
function handleEnable(command: string, ids: string[]) {
  deptApi.batchEnable({ deptId: ids }, JSON.parse(command)).then((response) => {
    if (response.status === 200) {
      if (command === "false") {
        ElMessage({
          message:
            t("common.successDisable") + response.data + t("common.stripData"),
          type: "success",
        });
      } else {
        ElMessage({
          message:
            t("common.successEnable") + response.data + t("common.stripData"),
          type: "success",
        });
      }
      tableHooks.getList();
      multipleTableRef.value?.clearSelection();
    }
  });
}

// 处理排序
function handleSort(sort: TableSort) {
  tableHooks.handleSort(sort.prop, sort.order);
}

// 查询数据.
tableHooks.getList();
</script>
